import useAsync from "@hooks/useAsync";

const DEFAULT_OPTIONS = {
  headers: { "Content-Type": "application/json" },
};

type FetchOptions = RequestInit;
type FetchDependencies = unknown[];

export default function useFetch(
  url: string,
  options: FetchOptions = {},
  dependencies: FetchDependencies = []
) {
  return useAsync(() => {
    return fetch(url, { ...DEFAULT_OPTIONS, ...options }).then((res) => {
      if (res.ok) return res.json();
      return res.json().then((json) => Promise.reject(json));
    });
  }, dependencies);
}
